<!-- users页面 -->
<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card区域 -->
    <el-card>
      <!-- 查询和添加用户区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
          >添加用户</el-button>

        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table
        :data="users"
        stripe
        border
      >
        <el-table-column
          type="index"
          label="#"
        ></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
        ></el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
        ></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showAssignDialogVisible(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeAddForm"
    >
      <!-- 对话框主体区域 -->
      <el-form
        :model="adduser"
        :rules="addUserRules"
        ref="resetFormRef"
      >
        <el-form-item
          label="用户名"
          label-width="100px"
          prop="username"
        >
          <el-input v-model="adduser.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          label-width="100px"
          prop="password"
        >
          <el-input
            v-model="adduser.password"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          label-width="100px"
          prop="email"
        >
          <el-input v-model="adduser.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          label-width="100px"
          prop="mobile"
        >
          <el-input v-model="adduser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUserToList()"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeEditForm"
    >
      <el-form
        :model="editUserInfo"
        :rules="editUserRules"
        ref="editUserRef"
      >
        <el-form-item
          label="用户名"
          label-width="100px"
          prop="username"
        >
          <el-input
            v-model="editUserInfo.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          label-width="100px"
          prop="email"
        >
          <el-input v-model="editUserInfo.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          label-width="100px"
          prop="mobile"
        >
          <el-input v-model="editUserInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editUserToList"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="assignDialogVisible"
      width="50%"
    >
      <div class="assignInfoDiv">
        <p>当前的用户：{{this.assignInfo.username}}</p>
        <p>当前的角色:{{this.assignInfo.role_name}}</p>
        <p>分配角色：
          <el-select
            v-model="selectRoleId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>

      </div>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="assignDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="setRole"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        // 查询参数
        query: "",
        // 页码
        pagenum: 1,
        // 每页的数据量
        pagesize: 2,
      },
      users: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制编辑用户对话框的显示与隐藏
      editDialogVisible: false,
      // 控制分配角色对话框的显示与隐藏
      assignDialogVisible: false,
      // 添加用户的信息
      adduser: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 编辑用户的信息
      editUserInfo: {},
      // 分配角色用户的信息
      assignInfo: {},
      // 角色列表
      roleList: [],
      // 选中的角色
      selectRoleId: "",
      // 增加用户的表单校验
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 8,
            max: 15,
            message: "长度在 8 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur",
          },
        ],
      },
      // 修改用户的表单校验
      editUserRules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
            message: "请输入合法手机号/电话号",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    // 获取用户列表
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("获取列表失败");
      this.users = res.data.users;
      this.total = res.data.total;
    },
    // 每页显示多条跳数据发生改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUsersList();
    },
    // 页码发生变化
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUsersList();
    },
    async changState(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.err("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    // 将添加的用户信息保存到后台并展现出来
    addUserToList() {
      this.$refs.resetFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请输入合法的信息！");
        const { data: res } = await this.$http.post("users", this.adduser);
        if (res.meta.status !== 201) return this.$message.error("创建用户失败");
        this.$message.success("创建用户成功");
        this.getUsersList();
        this.addDialogVisible = false;
      });
    },
    closeAddForm() {
      this.$refs.resetFormRef.resetFields();
    },
    // 编辑用户的对话框
    async editUser(userInfo) {
      const { data: res } = await this.$http.get(`users/${userInfo.id}`);
      this.editUserInfo = res.data;

      this.editDialogVisible = true;
    },
    closeEditForm() {
      this.$refs.editUserRef.resetFields();
    },
    editUserToList() {
      // 提交前先做表单的校验
      this.$refs.editUserRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请输入正确的信息！");
        const { data: res } = await this.$http.put(
          `users/${this.editUserInfo.id}`,
          { email: this.editUserInfo.email, mobile: this.editUserInfo.mobile }
        );
        if (res.meta.status !== 200) return this.$message.error("修改失败");
        this.$message.success("修改成功");
        this.getUsersList();
      });
      this.editDialogVisible = false;
    },
    // 删除用户
    deleteUser(id) {
      this.$confirm("此操作将永久删除该用户信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`);
          if (res.meta.status !== 200) return this.$message.error("删除失败！");
          this.getUsersList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 展示分配角色的对话框
    async showAssignDialogVisible(role) {
      this.assignInfo = role;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("请求角色列表失败！");
      this.roleList = res.data;
      this.assignDialogVisible = true;
    },
    // 设置用户角色
    async setRole() {
      const { data: res } = await this.$http.put(
        `users/${this.assignInfo.id}/role`,
        { id: this.assignInfo.id, rid: this.selectRoleId }
      );
      if (res.meta.status !== 200) return this.$message.error("设置角色失败！");
      this.$message.success("设置角色成功！");
      this.getUsersList();
      this.assignDialogVisible = false;
    },
  },
};
</script>

<style  scoped>
.assignInfoDiv {
  text-align: left;
}
</style>
